﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using VodafoneWP7.Resources;

namespace VodafoneWP7
{

    public struct testB
    {
        public string Name;
    }

    public enum AccountManagementType
    {
        Create,
        AskPassword,
        Edit,
        View
    }
    
    public partial class AccountsPage : PhoneApplicationPage
    {
        bool isTrial;
        List<Account> Accounts;
        AccountManagementType type;
        Account selectedAccount;
        List<AMessageService> Services;


        ApplicationBarIconButton B_save_changes, B_save_new_account, B_delete_account, B_cancel;
        public AccountsPage()
        {
            InitializeComponent();

            var prefix = App.CurrentTheme == App.Theme.Dark ? "\\Images\\dark\\" : "\\Images\\light\\";
            
            B_save_changes = new ApplicationBarIconButton(new Uri(prefix+"appbar.save.rest.png", UriKind.Relative)) { Text = Strings.Edit, IsEnabled = true };
            B_save_new_account = new ApplicationBarIconButton(new Uri(prefix+"appbar.save.rest.png", UriKind.Relative)) { Text = Strings.Edit, IsEnabled = true };

            B_delete_account = new ApplicationBarIconButton(new Uri(prefix+"appbar.delete.rest.png", UriKind.Relative)) { Text = Strings.Delete, IsEnabled = true };
            B_cancel = new ApplicationBarIconButton(new Uri(prefix+"appbar.cancel.rest.png", UriKind.Relative)) { Text = Strings.Delete, IsEnabled = true };
            

            B_save_changes.Click += new EventHandler(Confirm_Button_Click);
            B_save_new_account.Click +=new EventHandler(Save_Button_Click);
            B_cancel.Click+=new EventHandler(Cancel_Button_Click);
            B_delete_account.Click+= new EventHandler(Delete_Button_Click);
            

            Accounts = Storage.LoadAccounts();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            isTrial = App.isTrial();
                      
            Services = MessaggingServices.AvailableServices;
            MessaggingService_ContextMenu.Items.Clear();
            for (int i = 0; i < Services.Count; i++)
            {
                MenuItem menuItem = new MenuItem()
                {
                    //Header = MessaggingService.GetServiceName(Services[i])
                    Header = Services[i].GetName()
                };
                menuItem.Click += Services_Context_Menu_Click;
                MessaggingService_ContextMenu.Items.Add(menuItem);
            }
            //BuildAccountsList();
        }

        private void Services_Context_Menu_Click(object sender, RoutedEventArgs e)
        {
            //diceType1 = GetDiceType(sender, diceType1);
            //DiceTypeText1.Text = GetDiceTypeString(diceType1);
            try
            {
                MenuItem item = (MenuItem)sender;
                string s = (string)item.Header;

                for (int i = 0; i < Services.Count; i++)
                {

                    //if (s == MessaggingService.GetServiceName(Services[i]))
                    if (s == Services[i].GetName())
                    {
                        MessaggingService_Area.Text = s;
                        current_service_type = Services[i].type;
                        current_messagging_service = Services[i];
                        if (current_messagging_service.AllowCheckUserPasswordCorrectness())
                            TestPassword_Button.Visibility = System.Windows.Visibility.Visible;
                        else
                            TestPassword_Button.Visibility = System.Windows.Visibility.Collapsed;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
        
        private bool SaveNewAccount(bool isNew)
        {
            var focused = FocusManager.GetFocusedElement();
            if (focused is TextBox) ((TextBox)focused).GetBindingExpression(TextBox.TextProperty).UpdateSource();
            var prev_account = Accounts.IndexOf(Accounts.FirstOrDefault(a => a.ID == selectedAccount.ID));
            if (prev_account >= 0)
                Accounts.RemoveAt(prev_account);
            else
            {
                if (Accounts.Where(a => a.Name == selectedAccount.Name).Count() > 0)//Il nome di un nuovo account deve essere diverso da quelli gia esistenti;
                {
                    MessageBox.Show(Strings.AccountNameCannotBeEmpty);
                    return false;
                }
                prev_account = Accounts.Count;
            }            

            if (selectedAccount.Name == "")
            {
                MessageBox.Show(Strings.AccountNameCannotBeEmpty);
                return false;
            }
            if (selectedAccount.Username == "")
            {
                MessageBox.Show(Strings.AccountUserNameCannotBeEmpty);
                return false;
            }
            if (!selectedAccount.SavePassword)
                selectedAccount._password = "";

            Accounts.Insert(prev_account,selectedAccount);

            //MessageService service;
            if (current_messagging_service != null)
            {
                selectedAccount.MessagingService = current_service_type;
            }

            Storage.SaveAccounts(Accounts);
            return true;
        }

        private void Save_Button_Click(object sender, EventArgs e)
        {
            if (SaveNewAccount(true))
            {
                selectedAccount = null;
                NavigationService.GoBack();
            }
        }

        private void Delete_Button_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Strings.AreYouSureToDelete, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            if (selectedAccount != null)
            {

                Accounts.Remove(Accounts.First(a => a.Name == selectedAccount.Name));
                Storage.SaveAccounts(Accounts);

            }
            NavigationService.GoBack();
        }

        private void Cancel_Button_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }
        
        private void Confirm_Button_Click(object sender, EventArgs e)
        {
            SaveNewAccount(false);

            NavigationService.GoBack();
        }

        private void GestureListener_Tap(object sender, GestureEventArgs e)
        {
            if (type == AccountManagementType.AskPassword)
                return;
            Border border = sender as Border;
            ContextMenu contextMenu = ContextMenuService.GetContextMenu(border);
            if (contextMenu.Parent == null)
            {
                contextMenu.IsOpen = true;
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            type = (AccountManagementType)PhoneApplicationService.Current.State["AccountManagementType"];
            PhoneApplicationService.Current.State.Remove("AccountManagementType");

            ApplicationBar.Buttons.Clear();

            switch (type)
            {
                case AccountManagementType.Create:
                    EditAccountPivot.Header = Strings.CreateAccount;
                    selectedAccount = new Account();
                    ApplicationBar.Buttons.Add(B_save_new_account);
                    //ApplicationBar.Buttons.Add(B_cancel);
                    break;
                case AccountManagementType.AskPassword:
                    selectedAccount = (Account)PhoneApplicationService.Current.State["SelectedAccount"];
                    PhoneApplicationService.Current.State.Remove("SelectedAccount");
                    EditAccountPivot.Header = Strings.Password;
                    Name_Area.IsReadOnly = true;
                    Username_Area.IsReadOnly = true;

                    var binding = new System.Windows.Data.Binding();
                    SavePassword_Toggle.Visibility = System.Windows.Visibility.Collapsed;
                    TestPassword_Button.Visibility = System.Windows.Visibility.Collapsed;
                    Header_Label.Visibility = System.Windows.Visibility.Collapsed;
                    Header_Area.Visibility = System.Windows.Visibility.Collapsed;
                    AllowHeader_Toggle.Visibility = System.Windows.Visibility.Collapsed;
                   
                    break;
                case AccountManagementType.Edit:
                    EditAccountPivot.Header = Strings.EditAccount;
                    selectedAccount = (Account)PhoneApplicationService.Current.State["SelectedAccount"];
                    PhoneApplicationService.Current.State.Remove("SelectedAccount");
                    ApplicationBar.Buttons.Add(B_save_changes);
                    //ApplicationBar.Buttons.Add(B_cancel);
                    ApplicationBar.Buttons.Add(B_delete_account);
                    break;
                case AccountManagementType.View:
                    selectedAccount = (Account)PhoneApplicationService.Current.State["SelectedAccount"];
                    PhoneApplicationService.Current.State.Remove("SelectedAccount");
                    break;
                default:
                    break;
            }
            AccountForm.DataContext = selectedAccount;

        }


        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            DisableProgressBar();
            PhoneApplicationService.Current.State.Remove("SelectedAccount");
            if (selectedAccount != null)
                PhoneApplicationService.Current.State.Add("SelectedAccount", selectedAccount);
        }

        private string prev_header;
        private string prev_signature;
        
        private void Header_Area_KeyUp(object sender, KeyEventArgs e)
        {
            if (Header_Area.Text.Length >= Account.HEADER_MAX_LENGTH)
            {
                Header_Area.Text = prev_header;
                Header_Area.Select(prev_header.Length, 0);
            }
            else
                prev_header = Header_Area.Text;
        }

        //private void Signature_Area_KeyUp(object sender, KeyEventArgs e)
        //{
        //    if (Signature_Area.Text.Length >= Account.SIGNATURE_MAX_LENGTH)
        //    {
        //        Signature_Area.Text = prev_signature;
        //        Signature_Area.Select(prev_signature.Length, 0);
        //    }
        //    else
        //        prev_signature = Signature_Area.Text;
        //}

        private AMessageService current_messagging_service = null;
        private MessaggingServiceType current_service_type;
        private void TestPassword_Button_Click(object sender, RoutedEventArgs e)
        {
            if (!current_messagging_service.AllowCheckUserPasswordCorrectness())
                return;
            Account a = new Account();
            a.Username = Username_Area.Text;
            a.Password = Password_Area.Password;
            EnableProgressBar();
            TestPassword_Button.Visibility = System.Windows.Visibility.Collapsed;
            
            current_messagging_service.CheckUserPasswordCorrectness(a, DisableProgressBar, OnCheckSuccesfull, Dispatcher);

        }


        private void OnCheckSuccesfull()
        {
            DisableProgressBar();
            MessageBox.Show(Strings.CheckSuccesfull);
            TestPassword_Button.Visibility = System.Windows.Visibility.Visible;
        }

        #region PROGRESS_BAR

        private void EnableProgressBar()
        {
            ToggleProgressBar.IsEnabled = true;
            ToggleProgressBar.IsIndeterminate = true;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
        }
        private void DisableProgressBar()
        {
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            if(current_messagging_service!=null)
            TestPassword_Button.IsEnabled = current_messagging_service.AllowCheckUserPasswordCorrectness();
        }
        private void DisableProgressBar(string message)
        {
            MessageBox.Show(message);
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            if (current_messagging_service != null)
            TestPassword_Button.IsEnabled = current_messagging_service.AllowCheckUserPasswordCorrectness();
        }

        #endregion
    }
}